package com.technology.education.base

import android.net.Uri
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.data.model.*
import com.technology.education.ext.*
import com.technology.education.network.apiService
import com.tencent.android.tpush.XGPushManager
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.launch
import me.hgj.jetpackmvvm.ext.request
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


/**
 * 描述　:APP全局的Viewmodel，可以存放公共数据，当他数据改变时，所有监听他的地方都会收到回调,也可以做发送消息
 * 比如 全局可使用的 地理位置信息，账户信息，事件通知等，
 */
class AppViewModel : BaseViewModel() {
    val userInfo = MutableLiveData<UserInfoModel>()
    val wechatPayResult = MutableLiveData<Boolean>() //微信支付是否成功

    /**
     * 当前定位的城市信息
     */
    val city = MutableLiveData<String>()

    val paymentsStatus = MutableLiveData<String>("未缴纳")

    /**
     * 兑换规则
     */
    var exchangeRule: ExchangeRuleModel? = null

    /**
     * 获取个人信息
     * @param onlyData 是否只加载用户信息,若为false 则会在个人信息成功之后加载腾讯信息,并走登录流程
     * 默认为false
     */
    fun getInfo(onlyData: Boolean = false) {
        if (isLogin()) {
            request({ apiService.userInfo() }, success = {
                userInfo.postValue(it)
                paymentsStatus.postValue(if (it.depositState == "0") "未缴纳" else "已缴纳")
                saveData(SpKeys.USER_ID, it.id)
                AppData.USER_ID = it.id
                if (!onlyData) {
                    getIMSign()
                }

            })
        }

    }

    /**
     * 获取腾讯登录签名
     */
    private fun getIMSign() {
        request({ apiService.getUserSig() }, success = {
            AppData.IM_SIGN = it.userSig
            loginIM(it.userSig)
        }, error = {
            toast(it.errorMsg)
        })
    }

    /**
     * 退出登录
     */
    fun logout() {
        request({ apiService.logout() }, success = {})
    }

    /**
     * 上传图片
     */
    fun upload(selectedPhotos: List<Photo>, success: (List<String>) -> Unit) {
        var count = 0
        val builder = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
        Luban.with(appContext).load<String>(selectedPhotos.map {
            it.path
        }).ignoreBy(100)
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {

                }

                override fun onSuccess(file: File?) {
                    count++
                    file?.let {
                        val imageBody: RequestBody =
                            RequestBody.create(MediaType.parse("multipart/form-data"), file)
                        builder.addFormDataPart(
                            "file",
                            file.name,
                            imageBody
                        )
                    }
                    if (count == selectedPhotos.size) {
                        request({
                            apiService.uploadFile(builder.build().parts())
                        }, success = {
                            success.invoke(it)
                        }, isShowDialog = true)
                    }
                }

                override fun onError(e: Throwable?) {

                }

            }).launch()

    }

    fun pushMessage(content: String, title: String, id: String) {
        request(
            {
                apiService.pushMessage(
                    hashMapOf(
                        "messageType" to 1,
                        "toMemberId" to id,
                        "message" to hashMapOf<String, Any>("content" to content, "title" to title)
                    )
                )
            },
            success = {})
    }
}